package com.drinks.yiniang.ui.fragment.community;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.community.CommunityFollowAdapter;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.entity.comment.CommentSubmitJson;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.community.CommunityNewsJson;
import com.drinks.yiniang.entity.event.CommunityFollowEvent;
import com.drinks.yiniang.entity.event.ShopCartEvent;
import com.drinks.yiniang.io.api.CommunityApiIO;
import com.drinks.yiniang.ui.activity.community.CommunityCommentsActivity;
import com.drinks.yiniang.ui.activity.community.UserCommunityActivity;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.activity.shop.MfrsDetailActivity;
import com.drinks.yiniang.ui.widget.dialog.CommentBoxDialog;
import com.drinks.yiniang.ui.widget.dialog.ShareDialog;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.SharedPreUtils;
import com.hansen.library.ui.widget.refresh.MSwipeRefreshLayout;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.fragment.BaseLazyFragment;
import com.hansen.library.utils.ArithmeticUtil;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * 社区关注页面
 *
 * @author han
 * A simple {@link Fragment} subclass.
 */
public class CommunityFollowFragment extends BaseLazyFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.OnItemChildClickListener, CommunityFollowAdapter.OnCommunityRelatedGoodsClickListener,
        CommentBoxDialog.OnSendCommentListener, BaseQuickAdapter.RequestLoadMoreListener {

    //refresh
    private MSwipeRefreshLayout refresh_community_follow;
    //列表
    private BaseRecyclerView rcv_community_follow;

    private CommunityFollowAdapter mFollowAdapter;

    private CommentBoxDialog mCommentBoxDialog;

    //当前登录用户的id
    private String mCurrentLoginUserId;

    //重新刷新列表数据
    private boolean isNeedRefresh;

    private int mPages;

    public CommunityFollowFragment() {
        // Required empty public constructor
    }

    public static CommunityFollowFragment newInstance() {
        return new CommunityFollowFragment();
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_community_follow;
    }

    @Override
    protected void initView(View mView) {
        refresh_community_follow = mView.findViewById(R.id.refresh_community_follow);

        rcv_community_follow = mView.findViewById(R.id.rcv_community_follow);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        mCurrentLoginUserId = SharedPreUtils.getInstance().getUserID();

        initAdapter();
    }

    private void initAdapter() {
        rcv_community_follow.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_community_follow.addItemDecoration(ItemSpacesDecoration.getItemDPDecoration(10));

        mFollowAdapter = new CommunityFollowAdapter(mContext, new ArrayList<CommunityNewsJson.CommunityNewsList>());
        mFollowAdapter.setCenterEmpty(getLayoutInflater(), rcv_community_follow);
        mFollowAdapter.bindToRecyclerView(rcv_community_follow);
    }

    @Override
    protected void listener() {
        refresh_community_follow.setOnRefreshListener(this);
        mFollowAdapter.setOnItemChildClickListener(this);
        mFollowAdapter.setOnCommunityRelatedGoodsClickListener(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void widgetClick(View v) {

    }

    @Override
    protected void lazyLoadData() {
        getCommunityList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CommunityFollowEvent event) {
        isNeedRefresh = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isNeedRefresh) {
            getCommunityList();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isNeedRefresh && getUserVisibleHint()) {
            getCommunityList();
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        Intent mIntent;

        CommunityNewsJson.CommunityNewsList data = mFollowAdapter.getItem(position);

        if (data == null) {
            return;
        }

        switch (view.getId()) {
            case R.id.iv_community_follow_avatar://头像
            case R.id.tv_community_follow_nickname://昵称
                if(data.getFans_id() == null || data.getFans_id().equals(mCurrentLoginUserId)) {
                    return;
                }
                mIntent = new Intent(mContext, UserCommunityActivity.class);
                mIntent.putExtra(Constants.KeyUserId, data.getFans_id());
                startActivity(mIntent);
                break;
            case R.id.iv_community_follow_three_dot://举报分享
                ShareDialog dialog = ShareDialog.newInstance(data.getFans_id(), data.getId(), true, true);

                dialog.show(getChildFragmentManager(), Constants.TAG_SHARE_DIALOG);
                break;
            case R.id.tv_community_follow_collect://收藏心愿
                doCollect(data, position);
                break;
            case R.id.tv_community_follow_like://点赞
                doLike(data, position);
                break;
            case R.id.tv_community_follow_total_comments://全部评论
                mIntent = new Intent(mContext, CommunityCommentsActivity.class);
                mIntent.putExtra(Constants.KeyCommunityId, data.getId());
                startActivity(mIntent);
                break;
            case R.id.tv_community_follow_comments_add://评论
                mCommentBoxDialog = CommentBoxDialog.newInstance(position);
                mCommentBoxDialog.show(getChildFragmentManager(), Constants.TAG_COMMENTS_DIALOG);
                break;
            default:
                break;
        }
    }


    @Override
    public void onCommunityGoodsClick(String id, boolean isBrand) {
        Intent intent = new Intent();
        intent.setClass(mContext, isBrand ? MfrsDetailActivity.class : GoodsDetailsActivity.class);
        intent.putExtra(isBrand ? Constants.KeyId : Constants.KeyGoodsId, id);
        startActivity(intent);
    }

    @Override
    public void sendComment(String comment, final int position) {
        CommunityNewsJson.CommunityNewsList data = mFollowAdapter.getItem(position);

        if (data == null || StringUtils.isEmpty(data.getId())) {
            return;
        }

        if (StringUtils.isEmpty(comment)) {
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityComments(data.getId(), comment, null,
                new APIRequestCallback<CommentSubmitJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(CommentSubmitJson res) {
                        if(mCommentBoxDialog != null) {
                            mCommentBoxDialog.dismiss();
                        }

                        CommunityNewsJson.CommunityNewsList data = mFollowAdapter.getItem(position);

                        if(data == null) {
                            return;
                        }

                        if(data.getComment() == null) data.setComment(new ArrayList<CommunityNewsJson.CommunityNewsComment>());

                        if(data.getComment().size() >= 2) {
                            for(int i = data.getComment().size() - 1; i >= 0; i--) {
                                if(i >= 1) {
                                    data.getComment().remove(i);
                                }
                            }
                        }

                        CommunityNewsJson.CommunityNewsComment commentData = new CommunityNewsJson.CommunityNewsComment();
                        commentData.setCommunity_id(res.getData().getCommunity_id());
                        commentData.setContent(res.getData().getContent());
                        commentData.setId(res.getData().getId());
                        commentData.setNickname(res.getData().getNickname());

                        data.setComment_count(ArithmeticUtil.add(data.getComment_count(), 1));
                        data.getComment().add(0, commentData);

                        mFollowAdapter.setData(position, data);
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Constants.RESULT_CODE_NORMAL && requestCode == Constants.REQ_LOGIN_CODE) {
            getCommunityList();
        }
    }

    @Override
    public void onRefresh() {
        getCommunityList();
    }

    @Override
    public void onLoadMoreRequested() {
        CommunityApiIO.getInstance().getMyFollowCommunityNew(mPages, new APIRequestCallback<CommunityNewsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommunityNewsJson res) {
                if (mFollowAdapter == null) {
                    return;
                }

                mPages++;
                mFollowAdapter.addData(res.getData().getData());
                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mFollowAdapter.loadMoreComplete();
                } else {
                    mFollowAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mFollowAdapter.loadMoreEnd();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取社区动态列表
    private void getCommunityList() {
        if(!ActivityUtils.isLogined(this, mContext, true)) {
            refresh_community_follow.setRefreshing(false);
            return;
        }

        if (!refresh_community_follow.isRefreshing()) {
            showLoadingDialog();
        }

        mPages = 1;

        CommunityApiIO.getInstance().getMyFollowCommunityNew(mPages, new APIRequestCallback<CommunityNewsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommunityNewsJson res) {
                if (mFollowAdapter == null) {
                    return;
                }

                mPages++;
                mFollowAdapter.getData().clear();
                mFollowAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mFollowAdapter.loadMoreComplete();
                } else {
                    mFollowAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mFollowAdapter.loadMoreEnd();
            }

            @Override
            public void onComplete() {
                isNeedRefresh = false;
                refresh_community_follow.setRefreshing(false);
                dismissDialog();
            }
        });
    }

    private void doLike(final CommunityNewsJson.CommunityNewsList data, final int pos) {
        if (StringUtils.isEmpty(data.getId())) {
            ToastUtils.showShort(R.string.text_community_not_exist);
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityLike(data.getId(), new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if(CommonUtils.isArrayIndexOutOfBounds(mFollowAdapter.getData(), pos)) {
                    return;
                }

                data.setLike_count(res.getData());
                data.setIs_like(Constants.STATUS_GLOBAL_YES.equals(data.getIs_like()) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES);

                mFollowAdapter.setData(pos, data);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void doCollect(final CommunityNewsJson.CommunityNewsList data, final int pos) {
        if (StringUtils.isEmpty(data.getId())) {
            ToastUtils.showShort(R.string.text_community_not_exist);
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityCollect(data.getId(), new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if (CommonUtils.isArrayIndexOutOfBounds(mFollowAdapter.getData(), pos)) {
                    return;
                }

                data.setCollect_count(res.getData());
                data.setIs_collect(Constants.STATUS_GLOBAL_YES.equals(data.getIs_collect()) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES);

                mFollowAdapter.setData(pos, data);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onDestroy() {
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        isNeedRefresh = false;
        mCommentBoxDialog = null;
        super.onDestroy();
    }
}
